<template>
  <div class="app-container">
    <el-tabs v-model="activeTab" type="card">
      <!-- 首页统计指标配置 -->
      <el-tab-pane label="首页统计指标" name="indexStatistics">
        <el-card>
          <el-form :model="indexStatisticsForm" label-width="200px">
            <el-form-item label="选择统计指标">
              <el-select v-model="indexStatisticsForm.selectedIndicators" multiple placeholder="请选择统计指标"
                style="width: 100%">
                <el-option v-for="item in indicatorOptions" :key="item.monitorId" :label="item.monitorName"
                  :value="item.monitorId" />
              </el-select>
            </el-form-item>
            <el-form-item label="统计时间范围">
              <el-date-picker v-model="indexStatisticsForm.timeRange" type="datetimerange" range-separator="至"
                start-placeholder="开始时间" end-placeholder="结束时间" value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveIndexStatisticsValue">保存配置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>

      <!-- 管网合格率配置 -->
      <el-tab-pane label="管网合格率" name="qualifiedRate">
        <el-card>
          <el-form :model="qualifiedRateForm" label-width="200px">
            <el-form-item label="合格标准(%)">
              <el-input-number v-model="qualifiedRateForm.standard" :min="0" :max="100" :precision="2" :step="0.1"
                style="width: 100%" />
            </el-form-item>
            <el-form-item label="计算方式">
              <el-radio-group v-model="qualifiedRateForm.calculationMethod">
                <el-radio label="1">平均值</el-radio>
                <el-radio label="2">加权平均值</el-radio>
                <el-radio label="3">最小值</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="统计周期">
              <el-radio-group v-model="qualifiedRateForm.statisticalCycle">
                <el-radio label="1">每日</el-radio>
                <el-radio label="2">每周</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveQualifiedRate">保存配置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>

      <!-- 压力报警配置 -->
      <el-tab-pane label="压力报警" name="pressureAlarm">
        <el-card>
          <el-form :model="pressureAlarmForm" label-width="200px">
            <el-form-item label="报警时间段">
              <el-time-picker v-model="pressureAlarmForm.startTime" placeholder="开始时间" format="HH:mm"
                value-format="HH:mm" />
              <span class="mx-2">至</span>
              <el-time-picker v-model="pressureAlarmForm.endTime" placeholder="结束时间" format="HH:mm"
                value-format="HH:mm" />
            </el-form-item>
            <el-form-item label="压力阈值(MPa)">
              <el-input-number v-model="pressureAlarmForm.pressureThreshold" :min="0" :precision="2" :step="0.1"
                style="width: 200px" />
            </el-form-item>
            <el-form-item label="报警通知方式">
              <el-checkbox-group v-model="pressureAlarmForm.notificationMethods">
                <el-checkbox label="1">短信通知</el-checkbox>
                <el-checkbox label="2">邮件通知</el-checkbox>
                <el-checkbox label="3">APP推送</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="savePressureAlarmValue">保存配置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>

      <!-- 阶梯电价配置 -->
      <el-tab-pane label="阶梯电价" name="electricityPrice">
        <el-card>
          <!-- <div class="mb-4">
            <el-button type="primary" @click="showAddPriceDialog">
              <el-icon>
                <Plus />
              </el-icon>添加电价等级
            </el-button>
          </div> -->

          <el-table :data="electricityPriceList" border style="width: 100%">
            <el-table-column prop="level" label="电价等级" align="center" />
            <el-table-column prop="maxKwh" label="用电量上限(kWh)" align="center" />
            <el-table-column prop="price" label="电价(元/kWh)" align="center" />
            <el-table-column label="操作" align="center" width="150">
              <template #default="{ row }">
                <el-button size="small" @click="editPrice(row)">编辑</el-button>
                <!-- <el-button size="small" type="danger" @click="deletePrice(row.id)">删除</el-button> -->
              </template>
            </el-table-column>
          </el-table>

          <div class="mt-4">
            <el-button type="primary" @click="saveElectricityPrice">保存配置</el-button>
          </div>
        </el-card>
      </el-tab-pane>

      <!-- 行政区域配置 -->
      <el-tab-pane label="行政区域" name="administrativeArea">
        <el-card>
          <div class="mb-4">
            <el-button type="primary" @click="showAddAreaDialog">
              <el-icon>
                <Plus />
              </el-icon>新增区域
            </el-button>
          </div>

          <el-table :data="administrativeAreaList" border style="width: 100%">
            <el-table-column prop="province" label="省份" align="center" />
            <el-table-column prop="city" label="城市" align="center" />
            <el-table-column prop="district" label="区县" align="center" />
            <el-table-column label="操作" align="center" width="150">
              <template #default="{ row }">
                <el-button size="small" @click="editArea(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteArea(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 电价等级对话框 -->
    <el-dialog v-model="priceDialog.visible" :title="priceDialog.title" width="40%">
      <el-form :model="priceForm" label-width="120px">
        <el-form-item label="电价等级" prop="level">
          <el-input-number v-model="priceForm.level" :min="1" />
        </el-form-item>
        <el-form-item label="用电量上限(kWh)" prop="maxKwh">
          <el-input-number v-model="priceForm.maxKwh" :min="0" />
        </el-form-item>
        <el-form-item label="电价(元/kWh)" prop="price">
          <el-input-number v-model="priceForm.price" :min="0" :precision="2" :step="0.01" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="priceDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmPrice">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 行政区域对话框 -->
    <el-dialog v-model="areaDialog.visible" :title="areaDialog.title" width="40%">
      <el-form :model="areaForm" label-width="120px">
        <el-form-item label="省份" prop="province">
          <el-cascader v-model="areaValue" :options="areaOptions" @change="areaChange" :props="areaProps" placeholder="请选择省/市/区"
            style="width: 300px" clearable />
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="areaDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmArea">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getIndexStatistics,
  saveIndexStatistics,
  getNetWorkQualifiedRate,
  saveNetWorkQualifiedRate,
  getPressureAlarm,
  savePressureAlarm,
  getLadderElectricityPrice,
  saveLadderElectricityPrice,
  deleteLadderElectricityPrice,
  getAdministrativeAreaList,
  getAdministrativeArea,
  saveAdministrativeArea,
  getIndexStatisticsSelectList,
  getAdministrativeAreaSelectList,
  deleteAdministrativeArea
} from '@/api/dispatch/affair/otherSetting'

// 当前激活的标签页
const activeTab = ref('indexStatistics')

// 首页统计指标配置
const indexStatisticsForm = reactive({
  selectedIndicators: [],
  timeRange: []
})

const indicatorOptions = ref([])
const areaOptions = ref([])
const tareaValue = ref([]) 
const areaProps = {
  value: 'name',
  label: 'name',
  children: 'children'
}
// 管网合格率配置
const qualifiedRateForm = reactive({
  standard: 0,
  calculationMethod: '1',
  statisticalCycle: '1'
})

// 压力报警配置
const pressureAlarmForm = reactive({
  startTime: '',
  endTime: '',
  pressureThreshold: 0,
  notificationMethods: []
})

// 阶梯电价配置
const electricityPriceList = ref([])
const priceDialog = reactive({
  visible: false,
  title: '新增电价等级',
  mode: 'add'
})

const priceForm = reactive({
  id: null,
  level: 1,
  maxKwh: 0,
  price: 0
})

// 行政区域配置
const administrativeAreaList = ref([])
const areaDialog = reactive({
  visible: false,
  title: '新增行政区域',
  mode: 'add'
})

const areaForm = reactive({
  id: null,
  province: '',
  city: '',
  district: ''
})

const areaChange = (value) => {
  areaForm.province = value[0]
  areaForm.city = value[1]
  areaForm.district = value[2]
  console.log(areaForm);
  
}
// 初始化数据
const initData = async () => {
  try {
    // 获取首页统计指标配置
    const indexRes = await getIndexStatistics()
    if (indexRes.data) {
      indexStatisticsForm.selectedIndicators = indexRes.data.selectedIndicators.map(item => item.id)
      indexStatisticsForm.timeRange = [indexRes.data.startTime, indexRes.data.endTime]
    }

    // 获取管网合格率配置
    const qualifiedRateRes = await getNetWorkQualifiedRate()
    if (qualifiedRateRes.data) {
      Object.assign(qualifiedRateForm, qualifiedRateRes.data)
    }

    // 获取压力报警配置
    const pressureAlarmRes = await getPressureAlarm()
    if (pressureAlarmRes.data) {
      Object.assign(pressureAlarmForm, pressureAlarmRes.data)
      pressureAlarmForm.notificationMethods = pressureAlarmRes.data.notificationMethods.split(',')
    }

    // 获取阶梯电价配置
    const electricityPriceRes = await getLadderElectricityPrice()
    electricityPriceList.value = electricityPriceRes.data || []

    // 获取行政区域配置
    const administrativeAreaRes = await getAdministrativeArea()
    administrativeAreaList.value = administrativeAreaRes.data || []


    const { data } = await getIndexStatisticsSelectList();
    indicatorOptions.value = data;


    const { data: areaData } = await getAdministrativeAreaSelectList();
    areaOptions.value = areaData;
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  }
}

// 保存首页统计指标配置
const saveIndexStatisticsValue = async () => {
  try {
    const data = {
      selectedIndicators: indexStatisticsForm.selectedIndicators.map(id => ({ id })),
      startTime: indexStatisticsForm.timeRange[0],
      endTime: indexStatisticsForm.timeRange[1]
    }

    await saveIndexStatistics(data)
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 保存管网合格率配置
const saveQualifiedRate = async () => {
  try {
    await saveNetWorkQualifiedRate(qualifiedRateForm)
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 保存压力报警配置
const savePressureAlarmValue = async () => {
  try {
    const data = {
      ...pressureAlarmForm,
      notificationMethods: pressureAlarmForm.notificationMethods.join(',')
    }

    await savePressureAlarm(data)
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 显示添加电价等级对话框
const showAddPriceDialog = () => {
  priceDialog.title = '新增电价等级'
  priceDialog.mode = 'add'
  priceForm.id = null
  priceForm.level = electricityPriceList.value.length + 1
  priceForm.maxKwh = 0
  priceForm.price = 0
  priceDialog.visible = true
}

// 编辑电价等级
const editPrice = (row) => {
  priceDialog.title = '编辑电价等级'
  priceDialog.mode = 'edit'
  Object.assign(priceForm, row)
  priceDialog.visible = true

  
}

// 删除电价等级
const deletePrice = async (id) => {
    await deleteLadderElectricityPrice(id)
}

// 确认电价等级操作
const confirmPrice = () => {
  if (priceDialog.mode === 'add') {
    electricityPriceList.value.push({ ...priceForm })
  } else {
    const index = electricityPriceList.value.findIndex(item => item.id === priceForm.id)
    if (index !== -1) {
      electricityPriceList.value[index] = { ...priceForm }
    } 
  }
  priceDialog.visible = false
  saveElectricityPrice()
}

// 保存阶梯电价配置
const saveElectricityPrice = async () => {
  try {
    await saveLadderElectricityPrice(electricityPriceList.value)
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 显示添加行政区域对话框
const showAddAreaDialog = () => {
  areaDialog.title = '新增行政区域'
  areaDialog.mode = 'add'
  areaForm.id = null
  areaForm.province = ''
  areaForm.city = ''
  areaForm.district = ''
  areaDialog.visible = true
}

// 编辑行政区域
const editArea = (row) => {
  areaDialog.title = '编辑行政区域'
  areaDialog.mode = 'edit'
  Object.assign(areaForm, row)
  areaDialog.visible = true
}

// 删除行政区域
const deleteArea = async (row) => {


    await deleteAdministrativeArea(row.id)
   initData();
}

// 确认行政区域操作
const confirmArea = async () => {
  try {
    await saveAdministrativeArea(areaForm)

    if (areaDialog.mode === 'add') {
      administrativeAreaList.value.push({ ...areaForm })
    } else {
      const index = administrativeAreaList.value.findIndex(item => item.id === areaForm.id)
      if (index !== -1) {
        administrativeAreaList.value[index] = { ...areaForm }
      }
    }

    areaDialog.visible = false
    ElMessage.success('操作成功')
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 初始化
onMounted(() => {
  initData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb-4 {
  margin-bottom: 16px;
}

.mt-4 {
  margin-top: 16px;
}

.mx-2 {
  margin-left: 8px;
  margin-right: 8px;
}
</style>